import logging as log
import os
import sys

from django.core.wsgi import get_wsgi_application
from tornado.options import parse_command_line

import settings

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)
sys.path.append('..')

print(sys.path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
# 启动django
get_wsgi_application()
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi

from app.urls import urls


def ping_db():
    from app.models.models import Users
    print('ping db')
    Users.objects.first()


def main():
    parse_command_line()
    # asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    # AsyncIOMainLoop().install()

    ioloop = tornado.ioloop.IOLoop.instance()
    application = tornado.web.Application(urls, **settings.TORNADO_ENV)

    http_server = tornado.httpserver.HTTPServer(application, xheaders=True, max_buffer_size=500000000)
    http_server.listen(settings.PORT, "0.0.0.0")
    print('na2 server run on {}({}:{})'.format(settings.ENV, "0.0.0.0", settings.PORT))

    tornado.ioloop.PeriodicCallback(ping_db, int(1 * 1000)).start()


    # # if hasattr(settings, 'DB_PING_SECS'):
    # tornado.ioloop.PeriodicCallback(ping_db, int(10 * 1000)).start()
    #
    try:
        print('start')
        ioloop.start()
    except KeyboardInterrupt:
        print('error')
        ioloop.stop()


if __name__ == '__main__':
    main()
